package commands

import (
	"context"
	"fmt"
	"os"

	cli "github.com/urfave/cli/v3"

	"github.com/containerd/containerd"
	"github.com/containerd/containerd/namespaces"
)

var pruneCommand = &cli.Command{
	Name:      "prune",
	Usage:     "Remove all stopped containers",
	UsageText: "ruc prune",

	Action: prune,

	ErrWriter:       os.Stderr,
	CommandNotFound: commandNotFoundHandler,
	ExitErrHandler:  exitErrHandler,
}

func prune(ctx context.Context, cmd *cli.Command) error {
	client, err := containerd.New(
		containerdAddress,
		containerd.WithDefaultNamespace(namespaces.Default),
	)
	if err != nil {
		return err
	}
	defer client.Close()

	containers, _ := client.Containers(ctx)
	for _, container := range containers {
		task, err := container.Task(ctx, nil)
		if err != nil {
			// 如果 task 不存在，直接删除 container
			if err := container.Delete(ctx, containerd.WithSnapshotCleanup); err != nil {
				fmt.Fprintf(cmd.ErrWriter, "%q: %s\n", cmd.FullName(), err)
			}
			continue
		}

		status, err := task.Status(ctx)
		if err != nil {
			fmt.Fprintf(cmd.ErrWriter, "%q: %s\n", cmd.FullName(), err)
			continue
		}

		// 如果状态是已停止，则先删除任务，再删除容器并清理快照，删除过程中打印错误信息
		if status.Status == containerd.Stopped {
			if _, err := task.Delete(ctx); err != nil {
				fmt.Fprintf(cmd.ErrWriter, "%q: %s\n", cmd.FullName(), err)
				continue
			}

			if err := container.Delete(ctx, containerd.WithSnapshotCleanup); err != nil {
				fmt.Fprintf(cmd.ErrWriter, "%q: %s\n", cmd.FullName(), err)
			}
		}
	}

	return nil
}
